from PySide6.QtCore import QEvent
from PySide6.QtWidgets import QApplication

from uipy.mainUI import Ui_MainWindow as mw

from utils.clear import clearFile
from utils.img import ImageManager, drawGreyImg, DrawLinesAndGetImg
from utils.display3D import display3D


from pages.uploadFile import *
from pages.drawCurves import *
from pages.dataImg import *

class MyWindow(QMainWindow, mw):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        # 设置窗口为无边框和透明背景
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)

        # 初始化鼠标拖动变量,左键拖动改变窗口位置
        self._drag_position = None

        # 右键拖动放大显示数据成像
        self.dragging = False
        self.last_zoom_rect = None

        self.image_manager = ImageManager(self)

        self.bind()

        # 伪多文件上传功能
        self.currentFileName = ""
        self.currentFilePath = ""
        self.curves = []
        self.las = None

        self.curvesItemCnt=0
        self.checkBoxes=[]

    def bind(self):
        # 三个点
        self.max_sf.clicked.connect(self.toggle_full_screen)
        self.min_sf.clicked.connect(lambda: self.showMinimized())
        self.close_button.clicked.connect(lambda: self.close())

        # 导航栏
        self.file_button.clicked.connect(lambda: self.stackedWidget_main.setCurrentIndex(3))
        self.curve_button.clicked.connect(lambda: self.stackedWidget_main.setCurrentIndex(2))
        self.img_button.clicked.connect(lambda: self.stackedWidget_main.setCurrentIndex(1))

        # 顶部
        self.comboBox_fileList.currentIndexChanged.connect(self.selectFile)

        # page1
        self.btn_uploadFile.clicked.connect(lambda: uploadFile(self))

        # page2
        self.btn_drawCurves.clicked.connect(lambda: DrawLinesAndGetImg(self, self.las))

        # page3
        self.pushButton_drawImg.clicked.connect(lambda: drawGreyImg(self, self.las))
        self.pushButton_go3D.clicked.connect(display3D)
        self.pushButton_pickSin.clicked.connect(lambda: imgOperateSIN(self))

    def toggle_full_screen(self):
        if self.isFullScreen():
            # 如果当前是全屏模式，恢复到原来大小
            self.showNormal()
            self.resize(self.original_size)  # 恢复到原始大小
        else:
            # 如果当前不是全屏模式，保存当前大小并切换到全屏
            self.original_size = self.size()  # 保存当前大小
            self.showFullScreen()

    # 从文件列表下拉框中选择文件，实际就是重新上传一次
    def selectFile(self):
        current_text = self.comboBox_fileList.currentText()
        if current_text != self.currentFilePath:
            reSelectFile(self, current_text)

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self._drag_position = event.globalPosition().toPoint() - self.frameGeometry().topLeft()
            event.accept()
        elif event.button() == Qt.RightButton:
            self.dragging = True
            self.start_pos = event.position().toPoint()

    def mouseMoveEvent(self, event):
        if event.buttons() & Qt.RightButton and self.label_showGreyImg.pixmap().isNull():
            print("还没有成像")
            return
        label_geometry = self.label_showGreyImg.geometry()

        # 右键拖动
        if self.dragging and event.buttons() & Qt.RightButton:
            end_pos = event.position().toPoint()
            width = 30
            height = 20 # 固定放大区域大小为80x60像素
            x_in_label = max(0, min(end_pos.x() - width // 2, label_geometry.width() - width))
            y_in_label = max(0, min(end_pos.y() - height // 2, label_geometry.height() - height))

            # 将标签内的坐标转换为图像上的坐标
            pixmap_width = self.label_showGreyImg.pixmap().width()
            pixmap_height = self.label_showGreyImg.pixmap().height()
            scale_x = pixmap_width / label_geometry.width()
            scale_y = pixmap_height / label_geometry.height()
            x = int(x_in_label * scale_x)
            y = int(y_in_label * scale_y)

            self.last_zoom_rect = (x, y, width, height)
            self.update_zoomed_image(x, y, width, height)

        # 左键拖动
        if not self._drag_position:
            return
        if event.buttons() & Qt.LeftButton:
            self.move(event.globalPosition().toPoint() - self._drag_position)
            event.accept()

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            self._drag_position = None
            event.accept()
        elif event.button() == Qt.RightButton:
            self.dragging = False

    def resizeEvent(self, event: QEvent) -> None:
        # 调用父类的 resizeEvent 方法
        super().resizeEvent(event)

        # 更新所有已设置图片的 QLabel
        for label_name in self.image_manager.image_paths:
            self.image_manager.updateImage(label_name)

    def update_zoomed_image(self, x, y, width, height):
        zoom_pixmap = self.label_showGreyImg.pixmap().copy(x, y, width, height).scaled(300, 200, Qt.KeepAspectRatioByExpanding)
        self.label_zoom.setPixmap(zoom_pixmap)

if __name__ == '__main__':
    app = QApplication([])
    window = MyWindow()
    window.show()
    app.exec()

    clearFile('./runtime')